﻿Imports System.Data.SqlClient

Public Class frmMakeJournalVoucher

    Sub Calculate()
        If Me.GridVoucher.Rows.Count = 0 Then
            Me.txtCrd.Text = "0"
            Me.txtDep.Text = "0"
            Me.txtBalance.Text = "0"
        Else
            Try
                Dim Crd, Dep As Double
                Dim i As Integer

                ' Iterate through a dictionary
                For i = 0 To Me.GridVoucher.Rows.Count - 1
                    Dep = Dep + Me.GridVoucher.Rows(i).Cells(Me.DGColDebit.Index).Value
                    Crd = Crd + Me.GridVoucher.Rows(i).Cells(Me.DGColCredit.Index).Value
                Next

                If Crd = 0 Then
                    Me.txtCrd.Text = "0.00"
                Else
                    Me.txtCrd.Text = Format(Crd, "##,###.##")
                End If

                If Dep = 0 Then
                    Me.txtDep.Text = "0.00"
                Else
                    Me.txtDep.Text = Format(Dep, "##,###.##")
                End If

                If Crd - Dep = 0 Then
                    Me.txtBalance.Text = "0.00"
                Else
                    Me.txtBalance.Text = Format(CDbl(Crd - Dep), "##,###.##")
                End If
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.ErrProv.Clear()
        If Me.GridVoucher.Rows.Count = 0 Then
            Exit Sub
        ElseIf CDbl(Me.txtCrd.Text - Me.txtDep.Text) <> 0 Then
            ErrProv.SetError(Me.txtBalance, "Please complete the voucher")
            Exit Sub
        ElseIf ValidateDate(Me.DTPTrans.Value) = False Then
            Me.ErrProv.SetError(Me.DTPTrans, "Date isn't accepted")
        Else
            Try
                Me.Cursor = Cursors.WaitCursor

                'Validate rows
                Dim Valid As Boolean = True
                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        If row.Cells(Me.DGColAcc4.Index).Style.BackColor = Color.Salmon OrElse row.Cells(Me.DGColDescr.Index).Value = "" _
                        OrElse row.Cells(Me.DGColPayDetails.Index).Value = "" OrElse row.Cells(Me.CombBranch.Index).Value = "" OrElse _
                        row.Cells(Me.DGColDebit.Index).Style.BackColor = Color.Salmon Then
                            row.ErrorText = "Please fill in all fields"
                            Valid = False
                        Else
                            row.ErrorText = ""
                        End If
                    End If
                Next

                If Valid = False Then
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If

                Dim MoveNo As Integer
                Dim cmd As New SqlCommand
                Dim Trans As SqlTransaction

                cmd.Connection = cnn

                cnn.Open()
                Trans = cnn.BeginTransaction
                cmd.Transaction = Trans

                'Get Move No.
                cmd.CommandText = "Select IsNull(Max(MoveNo),0) From TempTransactions Where Branch=N'" & Branch & "' and Year(TransDate)= " & Me.DTPTrans.Value.Year
                MoveNo = CInt(cmd.ExecuteScalar) + 1

                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        cmd.CommandText = "Insert into TempTransactions (TransType,MoveNo,AccNo,Acc1,Acc2,Acc3,Acc4,Descr,ChNo,TotalOut,TotalIn," & _
                                          "SavedUser,TransDate,Branch) Values (@TransType,@MoveNo,@AccNo,@Acc1,@Acc2,@Acc3,@Acc4,@Descr,@ChNo," & _
                                          "@TotalOut,@TotalIn,@SavedUser,@TransDate,@Branch)"

                        cmd.Parameters.Clear()
                        cmd.Parameters.AddWithValue("@TransType", "Journal Voucher")
                        cmd.Parameters.AddWithValue("@MoveNo", MoveNo)
                        cmd.Parameters.AddWithValue("@AccNo", row.Cells(Me.DGColAccNo.Index).Value)
                        cmd.Parameters.AddWithValue("@Acc1", row.Cells(Me.DGColAcc1.Index).Value)
                        cmd.Parameters.AddWithValue("@Acc2", row.Cells(Me.DGColAcc2.Index).Value)
                        cmd.Parameters.AddWithValue("@Acc3", row.Cells(Me.DGColAcc3.Index).Value)
                        cmd.Parameters.AddWithValue("@Acc4", row.Cells(Me.DGColAcc4.Index).Value)
                        cmd.Parameters.AddWithValue("@Descr", row.Cells(Me.DGColDescr.Index).Value)
                        cmd.Parameters.AddWithValue("@ChNo", row.Cells(Me.DGColPayDetails.Index).Value)
                        cmd.Parameters.AddWithValue("@Branch", row.Cells(Me.CombBranch.Index).Value)
                        cmd.Parameters.AddWithValue("@TotalOut", CDbl(row.Cells(Me.DGColDebit.Index).Value))
                        cmd.Parameters.AddWithValue("@TotalIn", CDbl(row.Cells(Me.DGColCredit.Index).Value))
                        cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                        cmd.Parameters.AddWithValue("@TransDate", Me.DTPTrans.Value)
                        cmd.ExecuteNonQuery()
                    End If
                Next

                Trans.Commit()
                cnn.Close()

                MsgBox("Saved Successfully")

                Clear()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
            End Try
        End If
    End Sub

    Sub Clear()
        Me.GridVoucher.Rows.Clear()
        Me.txtCrd.Text = "0.00"
        Me.txtDep.Text = "0.00"
        Me.txtBalance.Text = "0.00"
        Me.GridVoucher.Focus()
    End Sub

    Private Sub DataGridView1_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles GridVoucher.RowsRemoved
        Calculate()
        ValidateGrid()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Clear()
    End Sub

    Private Sub GridVoucher_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellClick
        If e.ColumnIndex = Me.dgcolSearch.index Then
            Try
                Dim a As New frmSelectAccount
                a.ShowDialog()

                If SelAccNo <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(SelAccNo)

                    Me.GridVoucher.CurrentRow.Cells(0).Value = SelAccNo
                    Me.GridVoucher.CurrentRow.Cells(1).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(2).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(3).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(4).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try

        ElseIf e.ColumnIndex = Me.DGColDelete.Index Then
            If e.RowIndex < (Me.GridVoucher.Rows.Count - 1) Then
                Me.GridVoucher.Rows.RemoveAt(e.RowIndex)
            End If
        End If
    End Sub

    Private Sub GridVoucher_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellEndEdit
        If e.ColumnIndex = Me.DGColAccNo.Index Then
            Try
                If Me.GridVoucher.CurrentCell.Value <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(Me.GridVoucher.CurrentCell.Value)

                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc1.Index).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc2.Index).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc3.Index).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc4.Index).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                Else
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc1.Index).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc2.Index).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc3.Index).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(Me.DGColAcc4.Index).Value = ""
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try

        ElseIf e.ColumnIndex = Me.DGColDebit.Index Then
            If Me.GridVoucher.CurrentCell.Value = "" Then
                Me.GridVoucher.CurrentCell.Value = "0.00"
            Else
                Try
                    Me.GridVoucher.CurrentCell.Value = CDbl(Me.GridVoucher.CurrentCell.Value).ToString("N2")
                    If CDbl(Me.GridVoucher.CurrentCell.Value) <> 0 Then
                        Me.GridVoucher.CurrentRow.Cells(Me.DGColCredit.Index).Value = "0.00"
                    End If
                Catch ex As Exception
                    Me.GridVoucher.CurrentCell.Value = "0.00"
                End Try
            End If

        ElseIf e.ColumnIndex = Me.DGColCredit.Index Then
            If Me.GridVoucher.CurrentCell.Value = "" Then
                Me.GridVoucher.CurrentCell.Value = "0.00"
            Else
                Try
                    Me.GridVoucher.CurrentCell.Value = CDbl(Me.GridVoucher.CurrentCell.Value).ToString("N2")
                    If CDbl(Me.GridVoucher.CurrentCell.Value) <> 0 Then
                        Me.GridVoucher.CurrentRow.Cells(Me.DGColDebit.Index).Value = "0.00"
                    End If
                Catch ex As Exception
                    Me.GridVoucher.CurrentCell.Value = "0.00"
                End Try
            End If

        End If

        Calculate()
        ValidateGrid()
    End Sub

    Private Sub ChAccPath_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChAccPath.CheckedChanged
        If Me.ChAccPath.Checked = True Then
            Me.DGColAcc1.Visible = True
            Me.DGColAcc2.Visible = True
            Me.DGColAcc3.Visible = True
        ElseIf Me.ChAccPath.Checked = False Then
            Me.DGColAcc1.Visible = False
            Me.DGColAcc2.Visible = False
            Me.DGColAcc3.Visible = False
        End If
    End Sub

    Sub ValidateGrid()
        Try
            Me.Cursor = Cursors.WaitCursor

            For Each row As DataGridViewRow In Me.GridVoucher.Rows
                If row.Cells(4).Value = "" Then
                    row.Cells(4).Style.BackColor = Color.Salmon
                Else
                    row.Cells(4).Style.BackColor = row.DefaultCellStyle.BackColor
                End If

                If CDbl(row.Cells(9).Value) = 0 And CDbl(row.Cells(10).Value) = 0 Then
                    row.Cells(9).Style.BackColor = Color.Salmon
                    row.Cells(10).Style.BackColor = Color.Salmon

                ElseIf CDbl(row.Cells(9).Value) = 0 Or CDbl(row.Cells(10).Value) = 0 Then
                    row.Cells(9).Style.BackColor = row.DefaultCellStyle.BackColor
                    row.Cells(10).Style.BackColor = row.DefaultCellStyle.BackColor
                End If
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Sub FillBranches()
        Try
            Me.Cursor = Cursors.WaitCursor

            Me.CombBranch.Items.Clear()
            Dim Branches As ArrayList = GetBranches()

            For Each Branch As String In Branches
                Me.CombBranch.Items.Add(Branch)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub frmMakeJournalVoucher_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        FillBranches()
    End Sub
End Class
